package com.example.lt.controller;

import com.example.lt.constant.MessageConstant;
import com.example.lt.exception.LoginFailedException;
import com.example.lt.pojo.dto.AdminLoginDTO;
import com.example.lt.pojo.entity.Admin;
import com.example.lt.pojo.vo.AdminVO;
import com.example.lt.properties.JwtProperties;
import com.example.lt.result.Result;
import com.example.lt.service.AdminService;
import com.example.lt.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import static com.example.lt.constant.CommonConstant.USER_ID;

/**
 * @Author 小涛Tao
 * @Date: 2024/06/11/18:41
 * version 1.0 注释：
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin")
public class AdminController {

    private final AdminService adminService;

    private final JwtProperties jwtProperties;

    /**
     * 管理员登录
     * @param adminLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<AdminVO> adminLogin(@RequestBody AdminLoginDTO adminLoginDTO) {
        log.info("管理员登录：{}",adminLoginDTO);
        Admin admin = adminService.adminLogin(adminLoginDTO);
        if (admin == null) {
            throw new LoginFailedException(MessageConstant.ADMIN_LOGIN_FAIL);
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(USER_ID, admin.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getLoginSecretKey(),
                jwtProperties.getLoginTtl(),
                claims
        );

        AdminVO adminVO = AdminVO.builder()
                .id(admin.getId())
                .username(admin.getName())
                .token(token)
                .build();

        return Result.success(MessageConstant.ADMIN_LOGIN_SUCCESS, adminVO);
    }

}
